/*
 * @File    :   socket_client.js
 * @Time    :   2024/03/26 16:36:19
 * @Author  :   chakcy
 * @Email   :   947105045@qq.com
 * @description   :   socket 客户端
 */

const net = require('net');
const { encode, decode } = require('../base64')

class SocketClient {
    constructor(port) {
        this.port = port;
        this.client = null;
    }

    connect() {
        return new Promise((resolve, reject) => {
            this.client = net.createConnection({ port: this.port }, () => {
                console.log('Connected to server');
                resolve();
            });

            this.client.on('error', (err) => {
                reject(err);
            });
        });
    }

    send(message) {
        if (!this.client || !this.client.writable) {
            throw new Error('Not connected or client is not writable');
        }
        this.client.write(message, (err) => {
            if (err) {
                console.error('Error while sending message:', err);
            }
        });
    }

    disconnect() {
        if (this.client) {
            this.client.end();
            this.client = null;
        }
    }

    onMessage(callback) {
        if (this.client) {
            this.client.on('data', (data) => {
                callback(data.toString());
            });
        } else {
            throw new Error('Not connected to the server');
        }
    }

    onError(callback) {
        if (this.client) {
            this.client.on('error', callback);
        } else {
            throw new Error('Not connected to the server');
        }
    }
}

async function sendMultipleSocketRequests(requests) {
    const promises = requests.map(request => {
        return new Promise((resolve, reject) => {
            const client = new SocketClient(request.port)
            client.connect().then(() => {
                client.onMessage((message) => {
                    message = JSON.parse(decode(message))
                    // console.log(`Received from server: ${message}`);
                    client.disconnect(); // 收到消息后断开连接  
                    resolve(message)
                });

                client.onError((error) => {
                    console.error('Client error:', error);
                    client.disconnect(); // 发生错误时断开连接  
                    reject(error)
                });
                client.send(encode(request.message));
            }).catch((error) => {
                console.error('Connection error:', error);
                client.disconnect(); // 连接失败时断开连接  
                reject(error)
            });
        })
    })
    try {
        const responses = await Promise.all(promises)
        return responses
    } catch (error) {
        throw error
    }
}

module.exports = {
    SocketClient,
    sendMultipleSocketRequests
}
